import { EventBus } from '../EventBus';
import { Scene } from 'phaser';
import { webSocketManager } from '../WebSocketManager';

export class MainMenu extends Scene
{
    logoTween;

    constructor ()
    {
        super('MainMenu');
    }

    create ()
    {
        this.add.image(512, 384, 'background');

        this.logo = this.add.image(512, 200, 'logo').setDepth(100);

        this.add.text(512, 320, 'Agar.io Clone', {
            fontFamily: 'Arial Black', fontSize: 48, color: '#ffffff',
            stroke: '#000000', strokeThickness: 8,
            align: 'center'
        }).setDepth(100).setOrigin(0.5);

        // 创建用户名输入框背景
        const inputBg = this.add.rectangle(512, 380, 300, 40, 0xffffff, 0.9);
        inputBg.setStrokeStyle(2, 0x000000);
        inputBg.setDepth(100);

        // 创建用户名输入框
        this.usernameInput = document.createElement('input');
        this.usernameInput.type = 'text';
        this.usernameInput.placeholder = '输入用户名';
        this.usernameInput.style = `
            position: absolute;
            left: ${512 - 150}px;
            top: ${380 - 20}px;
            width: 300px;
            height: 40px;
            border: none;
            border-radius: 5px;
            padding: 0;
            font-size: 16px;
            font-family: Arial, sans-serif;
            background: transparent;
            color: #000000;
            outline: none;
            z-index: 1000;
            pointer-events: auto;
            box-sizing: border-box;
            text-align: center;
            line-height: 40px;
        `;
        this.usernameInput.value = 'Player'; // 默认用户名
        document.body.appendChild(this.usernameInput);

        // 确保输入框可以接收焦点和点击事件
        this.usernameInput.addEventListener('click', (event) => {
            event.stopPropagation();
        });
        this.usernameInput.addEventListener('mousedown', (event) => {
            event.stopPropagation();
        });
        this.usernameInput.addEventListener('focus', (event) => {
            event.stopPropagation();
        });

        // 延迟一下确保输入框完全加载
        setTimeout(() => {
            this.usernameInput.focus();
            // 选中默认文本，方便用户直接输入
            this.usernameInput.select();
        }, 100);

        // 创建确定按钮
        this.startButton = this.add.rectangle(512 + 160, 380, 80, 40, 0x00ff00);
        this.startButton.setStrokeStyle(2, 0x000000);
        this.startButton.setDepth(100);

        this.startButtonText = this.add.text(512 + 160, 380, '开始', {
            fontFamily: 'Arial', fontSize: 18, color: '#000000',
            stroke: '#ffffff', strokeThickness: 1,
            align: 'center'
        }).setDepth(100).setOrigin(0.5);

        // 添加按钮交互
        this.startButton.setInteractive();
        this.startButton.on('pointerdown', () => {
            this.startGame();
        });
        this.startButton.on('pointerover', () => {
            this.startButton.setFillStyle(0x00dd00);
        });
        this.startButton.on('pointerout', () => {
            this.startButton.setFillStyle(0x00ff00);
        });

        this.add.text(512, 420, 'Controls:', {
            fontFamily: 'Arial', fontSize: 20, color: '#ffffff',
            stroke: '#000000', strokeThickness: 3,
            align: 'center'
        }).setDepth(100).setOrigin(0.5);

        this.add.text(512, 450, 'Move: Mouse | Split: Space', {
            fontFamily: 'Arial', fontSize: 16, color: '#ffffff',
            stroke: '#000000', strokeThickness: 2,
            align: 'center'
        }).setDepth(100).setOrigin(0.5);

        this.add.text(512, 470, 'Collect colorful stars to grow | Split to multiply', {
            fontFamily: 'Arial', fontSize: 16, color: '#ffffff',
            stroke: '#000000', strokeThickness: 2,
            align: 'center'
        }).setDepth(100).setOrigin(0.5);

        this.add.text(512, 490, 'Avoid red circles when size > 100!', {
            fontFamily: 'Arial', fontSize: 14, color: '#ff0000',
            stroke: '#000000', strokeThickness: 2,
            align: 'center'
        }).setDepth(100).setOrigin(0.5);

        // 初始化WebSocket连接
        webSocketManager.connect();

        // 添加回车键监听器
        this.usernameInput.addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                this.startGame();
            }
        });

        // 禁用Phaser在输入框区域的点击事件
        this.input.on('pointerdown', (pointer) => {
            const inputRect = this.usernameInput.getBoundingClientRect();
            if (pointer.x >= inputRect.left && pointer.x <= inputRect.right &&
                pointer.y >= inputRect.top && pointer.y <= inputRect.bottom) {
                // 如果点击在输入框区域内，阻止Phaser处理这个事件
                this.usernameInput.focus();
                return false;
            }
        });

        // 创建一个透明的覆盖层来捕获输入框区域的点击事件
        const inputOverlay = document.createElement('div');
        inputOverlay.style.cssText = `
            position: absolute;
            left: ${512 - 150}px;
            top: ${380 - 20}px;
            width: 300px;
            height: 40px;
            z-index: 999;
            pointer-events: auto;
            background: transparent;
        `;
        inputOverlay.addEventListener('click', (event) => {
            event.stopPropagation();
            this.usernameInput.focus();
        });
        document.body.appendChild(inputOverlay);
        
        // 保存引用以便后续清理
        this.inputOverlay = inputOverlay;
        
        EventBus.emit('current-scene-ready', this);
    }

    startGame() {
        if (this.logoTween)
        {
            this.logoTween.stop();
            this.logoTween = null;
        }

        // 获取用户名
        const username = this.usernameInput.value.trim() || 'Player';
        
        // 移除输入框和覆盖层
        if (this.usernameInput && this.usernameInput.parentNode) {
            this.usernameInput.parentNode.removeChild(this.usernameInput);
        }
        if (this.inputOverlay && this.inputOverlay.parentNode) {
            this.inputOverlay.parentNode.removeChild(this.inputOverlay);
        }

        // 发送游戏开始消息到Netty服务器
        webSocketManager.sendGameStart(username);

        // 发送玩家加入消息
        webSocketManager.sendMessage({
            type: 'player_join',
            data: {
                username: username,
                timestamp: Date.now()
            }
        });

        // 将用户名传递给游戏场景
        this.scene.start('Game', { username: username });
    }

    changeScene ()
    {
        this.startGame();
    }

    moveLogo (reactCallback)
    {
        if (this.logoTween)
        {
            if (this.logoTween.isPlaying())
            {
                this.logoTween.pause();
            }
            else
            {
                this.logoTween.play();
            }
        }
        else
        {
            this.logoTween = this.tweens.add({
                targets: this.logo,
                x: { value: 750, duration: 3000, ease: 'Back.easeInOut' },
                y: { value: 80, duration: 1500, ease: 'Sine.easeOut' },
                yoyo: true,
                repeat: -1,
                onUpdate: () => {
                    if (reactCallback)
                    {
                        reactCallback({
                            x: Math.floor(this.logo.x),
                            y: Math.floor(this.logo.y)
                        });
                    }
                }
            });
        }
    }
}
